import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type { workAreaEnum } from '~/store/assetManagement/assetAreaManage/typings'
import type { RoadManageDataItemType, RoadManageStateType, equipmentType } from './typings'
import { defineComponent, reactive, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
// import dayjs from 'dayjs'
import {
  ElCard,
  ElSpace,
  ElLink,
  ElButton,
  ElIcon,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElMessageBox,
  ElMessage
} from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import AliIcon from '~/components/AliIocn'
import ProSaasTable from '~/components/ProSaasTable'
import RoadManegeOptions from './options' // 新增编辑
import RelevenceModal from './relevenceModal' // 关联设施

import RoadManageImportModal from './importModal' // 导入
import useVuexGetters from '~/hooks/useVuexGetters'
import { EL_SPACE_SIZE_SECOND_GEAR } from '~/utils/const'
import { handleTrim } from '~/utils/util'
import styles from '../../index.module.scss'

export default defineComponent(function roadManage() {
  const store = useStore()
  const proSaasTableRef = ref<ProSaasTableExposeType>() // 表格
  const isChecked = ref()
  const oneChecked = ref()
  const formValues = reactive<RoadManageDataItemType>({}) // 表单 用于查询
  const state = reactive<RoadManageStateType>({
    modalVisible: false,
    importVisible: false,
    record: {},
    relevenceVisible: false
  })

  const userState = useVuexGetters('user', ['permission'])
  const assetWorkAreaState = useVuexGetters('assetWorkArea', ['workAreaSelectList']) // 所属区域

  onMounted(() => {
    // 获取所属区域下拉列表
    store.dispatch('assetWorkArea/GetWorkAreaSelectListByUser')
  })

  // 打开操作弹框
  const handleChangeOptionsModal = (
    type: RoadManageStateType['type'],
    record?: RoadManageDataItemType
  ) => {
    state.record = record || {}
    state.type = type
    state.modalVisible = !state.modalVisible
    if (!state.modalVisible) proSaasTableRef.value!?.toSearch()
  }

  // 打开关联设施弹框
  const handleRelevanceOptionsModal = (record?: RoadManageDataItemType) => {
    state.record = record || {}
    state.relevenceVisible = !state.relevenceVisible
    if (!state.relevenceVisible) proSaasTableRef.value!?.toSearch()
  }

  // 切换导入弹框
  const handleChangeImprotModal = () => {
    state.importVisible = !state.importVisible
    if (!state.importVisible) proSaasTableRef.value!?.toSearch()
  }

  // 执行删除操作
  // const handleDeleteSelectedData = async (params: string) => {
  //   await store
  //     .dispatch('roadManage/DeleteRoadManageInfo', {
  //       ids: params
  //     })
  //     .then((res) => {
  //       if (res?.code === 200) {
  //         proSaasTableRef.value!?.clearSelection?.()
  //         proSaasTableRef.value!?.toSearch()
  //         ElMessage({ type: 'success', message: '操作成功' })
  //       }
  //     })
  // }

  // 打开删除消息确认框
  const handleOpenDeleteConfirm = (record?: RoadManageDataItemType) => {
    if (!record && !proSaasTableRef.value!.selecteds?.length) {
      ElMessage({ type: 'warning', message: '请选择要删除的数据' })
      return
    }
    const params =
      record?.id || proSaasTableRef.value!.selecteds?.map?.((item) => item!?.id)?.join(',')
    isChecked.value = proSaasTableRef?.value?.selecteds.filter(
      (item) => item.relDistribution + item.relLampBase + item.relLampPost > 0
    )
    oneChecked.value = Number(
      record?.relDistribution! + record?.relLampBase! + record?.relLampPost!
    )
    ElMessageBox({
      title: '确认提示',
      message: (
        <section class={styles['delete-confirm-box']}>
          {
            <p class="delete-title">
              {isChecked.value.length > 0 || oneChecked.value > 0
                ? '道路关联的有设施数据，删除后将取消关联，确认删除？'
                : '确认删除数据？'}
            </p>
          }
        </section>
      ),
      showCancelButton: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      cancelButtonClass: 'el-button--primary is-plain',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(async () => {
        await store
          .dispatch('roadManage/DeleteRoadManageInfo', { id: params })
          .then(async (result) => {
            if (result?.success) ElMessage({ type: 'success', message: '操作成功' })
            proSaasTableRef.value!?.toSearch()
          })
      })
      .catch(() => {})
  }

  // 按回车搜索列表
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') proSaasTableRef.value!?.toSearch()
  }

  // 清空搜索
  const clearSearchTable = async () => {
    if (formValues.name === '') {
      delete formValues.name // 道路名称
    }
    if (formValues.workAreaId === '') {
      delete formValues.workAreaId // 所属区域
    }
    setTimeout(() => {
      proSaasTableRef.value!?.toSearch()
    }, 100)
  }

  // 关联设备跳转
  const handleChangePage = (record?: RoadManageDataItemType, type?: equipmentType['type']) => {
    // 配电设施
    if (type === 'facility') {
      store.dispatch('user/MatchRouterOptionsJumpAddress', {
        path: '/asset_management/facility_management/power_distribution_facilities',
        query: { name: record?.name, id: record?.id }
      })
    }
    // 灯
    if (type === 'lamp') {
      store.dispatch('user/MatchRouterOptionsJumpAddress', {
        path: '/asset_lamp_base',
        query: { name: record?.name, id: record?.id }
      })
    }
    // 灯杆
    if (type === 'lamppost') {
      store.dispatch('user/MatchRouterOptionsJumpAddress', {
        path: '/asset_lamp_post',
        query: { name: record?.name, id: record?.id }
      })
    }
  }

  const columns: TableColumnProps<RoadManageDataItemType>[] = [
    {
      label: '道路名称',
      prop: 'name',
      minWidth: 180,
      fixed: 'left',
      unFixed: true,
      disabled: true,
      sortable: true,
      showOverflowTooltip: true
    },
    {
      label: '所属区域',
      prop: 'workAreaName',
      minWidth: 180,
      sortable: true
    },
    {
      label: '关联配电设施',
      prop: 'relDistribution',
      minWidth: 180,
      sortable: true,
      render: (option, value) => (
        <ElLink onClick={() => handleChangePage(option.row, 'facility')} type="primary">
          &nbsp;{value}
        </ElLink>
      )
    },
    {
      label: '关联灯杆',
      prop: 'relLampPost',
      minWidth: 180,
      sortable: true,
      render: (option, value) => (
        <ElLink onClick={() => handleChangePage(option.row, 'lamppost')} type="primary">
          &nbsp;{value}
        </ElLink>
      )
    },
    {
      label: '关联灯具',
      prop: 'relLampBase',
      minWidth: 180,
      sortable: true,
      render: (option, value) => (
        <ElLink onClick={() => handleChangePage(option.row, 'lamp')} type="primary">
          &nbsp;{value}
        </ElLink>
      )
    },
    {
      label: '更新时间',
      prop: 'updateTime',
      minWidth: 220,
      sortable: true
    },
    {
      label: '操作',
      prop: 'options',
      align: 'center',
      fixed: 'right',
      unFixed: true,
      disabled: true,
      minWidth: 220,
      render: ({ row }) => (
        <ElSpace size={EL_SPACE_SIZE_SECOND_GEAR}>
          {userState.permission.value.has('assets_road_update') && (
            <ElLink type="primary" onClick={() => handleChangeOptionsModal('update', row)}>
              <AliIcon type="icon-bianji" />
              &nbsp; 编辑
            </ElLink>
          )}
          {userState.permission.value.has('assets_road_facilities') && (
            <ElLink type="primary" onClick={() => handleRelevanceOptionsModal(row)}>
              <AliIcon type="icon-a-guanlian1" />
              &nbsp; 关联设施
            </ElLink>
          )}
          {userState.permission.value.has('assets_road_remove') && (
            <ElLink type="primary" onClick={() => handleOpenDeleteConfirm(row)}>
              <AliIcon type="icon-shanchu" />
              &nbsp; 删除
            </ElLink>
          )}
        </ElSpace>
      )
    }
  ]
  return () => (
    <ElCard shadow="never" class="covered-with-content">
      <ProSaasTable<RoadManageDataItemType>
        tableId="roadManage"
        ref={proSaasTableRef}
        columns={columns}
        rowKey="id"
        hasSelection
        dispatchType="roadManage/GetRoadManageList"
        headerTitle={
          <>
            {userState.permission.value.has('assets_road_add') && (
              <ElButton type="primary" onClick={() => handleChangeOptionsModal('add')}>
                <ElIcon>
                  <Plus />
                </ElIcon>
                &nbsp; 新增
              </ElButton>
            )}
            {userState.permission.value.has('assets_road_remove') && (
              <ElButton type="danger" onClick={() => handleOpenDeleteConfirm()}>
                <AliIcon type="icon-shanchu" />
                &nbsp; 删除
              </ElButton>
            )}
            {userState.permission.value.has('assets_road_import') && (
              <ElButton type="primary" onClick={() => handleChangeImprotModal()}>
                <AliIcon type="icon-daoru" />
                &nbsp; 导入
              </ElButton>
            )}
          </>
        }
        searchParams={{
          name: formValues.name === '' ? undefined : formValues.name && handleTrim(formValues.name)
        }}
        searchFormProps={{
          model: formValues
        }}
        searchformResponsiveCol={[
          <ElFormItem key="name" prop="name">
            <ElInput
              v-model={formValues.name}
              {...{ maxlength: 20 }}
              placeholder="道路名称"
              clearable
              onKeydown={handleKeyDownEnterSubmitForm}
              onClear={clearSearchTable}
            />
          </ElFormItem>,
          <ElFormItem key="workAreaId" prop="workAreaId">
            <ElSelect
              v-model={formValues.workAreaId}
              placeholder="所属区域"
              clearable
              filterable
              onClear={clearSearchTable}
              onChange={() => {
                proSaasTableRef.value!?.toSearch()
              }}
            >
              {assetWorkAreaState.workAreaSelectList?.value?.map((item: workAreaEnum) => (
                <ElOption key={item?.id} label={item?.name} value={item?.id!} />
              ))}
            </ElSelect>
          </ElFormItem>
        ]}
      />
      {state.importVisible && <RoadManageImportModal doCancel={handleChangeImprotModal} />}
      {state.modalVisible && (
        <RoadManegeOptions
          record={state.record}
          type={state.type}
          visible={state.modalVisible}
          cancel={handleChangeOptionsModal}
        />
      )}
      {state.relevenceVisible && (
        <RelevenceModal
          record={state.record}
          visible={state.relevenceVisible}
          cancel={handleRelevanceOptionsModal}
        />
      )}
    </ElCard>
  )
})
